var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { expressjwt: expressJWT } = require("express-jwt");
var convRouter = require('./routes/conversation');
var messRouter = require('./routes/message')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors())
app.use(
  expressJWT({ secret: "five_612_apitokenkey", algorithms: ["HS256"] }).unless({
    path: [
      "/phoneReset",//手机号重置密码接口
      "/emailReset",//邮箱重置密码接口
      "/email",//发送邮件接口
      "/Phonelogin",//手机号登录接口
      "/login",//用户登录接口
      '/register',//用户注册接口
      { url: /^\/getCode/, methods: ["POST"] },//获取验证码接口
      '/refresh',//刷新token接口
      { url: /^\/upload/, methods: ["GET"] }//文件上传接口

    ], // 跳过token验证
  })
);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/conv', convRouter);
app.use('/mess', messRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  const authorization = req.headers["authorization"];
  //判断是否携带token
  if (!authorization) {
    return res.status(400).json({
      code: 20000,
      msg: "用户未登录",
    });
  }
  //判断token是否可用
  if (err) {
    if (err.name === "UnauthorizedError") {
      console.log(err);
      return res.status(400).json({
        code: 20000,
        msg: "登录过期，请重新登录--",
      });
    }
  }
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
